"use strict";
var q = require('q');
var models = require('./../models');
var co = require('co');
var moment = require('moment');
var EventEmitter = require('events').EventEmitter;
var Dist = require('../serialbootstrap/index').Dist;
var chalk = require('chalk');
/** 
 * 测距仪的帮助类
 */
class DistHelper extends Dist.DistController {
    /** 
     * @param {object} option 初始化参数,包括com,device:DistDeviceConfig
     */
    constructor(option) {
        super(option.com);
        /** 配置参数 */
        this.option = option;
        /** 每段顶管开始顶之前的初始的距离 */
        this._initialDist = NaN;
        /** 
         * 是否可以测量
         */
        this.enabled = true;
        /** 
         * 测距仪设备
         */
        this.device = this.option.device;
        this.deviceList = [this.option.device.deviceId];
    }
    
    /** 初始化com */
    initial() {

    }
    
    /** 
     * 循环测量,不叫停永远不停
     */
    _survey() {
        var _this = this;
        return co(function* () {
            if (!_this.enabled) {
                console.log(chalk.green('测距仪测量已经停止'));
                yield _this.closePort();
                return;
            }
            var results = yield _this.survey();
            var result = results[0].distance;
            //测量到结果了
            if (result) {
                console.log(chalk.gray('测距结果:') + chalk.blue(result) + ' ' + moment().format('YYYY-MM-DD HH:mm:ss'));
                if (isNaN(_this._initialDist)) {
                    _this._initialDist = result;
                }
                if (result >= _this._initialDist) {//验证测量结果是否符合常理
                    yield models.DistMileResult.create({
                        configId: _this.option.device.id,
                        deviceId: _this.option.device.deviceId,
                        value: result - _this._initialDist,
                        date: new Date()
                    });
                    yield models.DistDeviceResult.create({
                        configId: _this.option.device.id,
                        deviceId: _this.option.device.deviceId,
                        value: result,
                        date: new Date()
                    });
                    _this._initialDist = result;
                }
                yield q.delay(1000 * 10); //间隔10秒后再测
            }
            yield _this._survey();
        });
    }
    
    /** 
     * 开始观测,并把数据存入数据库
     */
    startSurvey() {
        try {
            if (this.isWorking) return;
            this.emit('distsurveystart');
            this._initialDist = NaN;
            this.enabled = true;
            this._survey();
        } catch (error) {
            console.log(error);
        }
    }
    
    /** 
     * 设置为不可观测状态,一般为换顶管时
     */
    stopSurvey() {
        this.enabled = false;
        this.emit('distsurveystop');
    }
}
module.exports = DistHelper;